#!/bin/bash

WORKSPACE=$(cd $(dirname $0)/; pwd)
# echo $WORKSPACE
cd $WORKSPACE

mkdir -p var

module=agent
app=server.py
conf=cfg.json
pidfile=var/app.pid
logfile=var/app.log
cronpid=var/cron.pid
cronfile=var/cron.log

function check_pid() {
    if [ -f $pidfile ];then
        pid=`cat $pidfile`
        if [ -n $pid ]; then
            running=`ps -p $pid|grep -v "server.py" |wc -l`
            return $running
        fi
    fi
    return 0
}

function cron() {
    nohup python cron.py > $cronfile &
    sleep 1
    running=`ps -p $! | grep -v "cron.py" | wc -l`
    if [ $running -gt 0 ];then
        echo $! > $cronpid
        echo "cron started..., pid=$!"
    fi
}

function start() {
    check_pid
    running=$?
    if [ $running -gt 0 ];then
        echo -n "$app now is running already, pid="
        cat $pidfile
        return 1
    fi

    nohup python server.py > $logfile &
    sleep 1
    running=`ps -p $! | grep -v "server.py" | wc -l`
    if [ $running -gt 0 ];then
        echo $! > $pidfile
        echo "$app started..., pid=$!"
    else
        echo "$app failed to start."
        return 1
    fi
}

function stop() {
    pid=`cat $pidfile`
    kill $pid
    rm -f $pidfile
    echo "$app stoped..."
}

function restart() {
    stop
    sleep 1
    start
}

function status() {
    check_pid
    running=$?
    if [ $running -gt 0 ];then
        echo started
    else
        echo stoped
    fi
}

function create_plugin() {
    if [[ $# != 3 ]]
    then
        echo 'plz input plugin folder name or env eg:native/common'
        exit 1
    fi

    if [[ -d plugins/$2 ]]
    then
        mkdir -p plugins/$2/$3
        touch plugins/$2/$3/__init__.py
        touch plugins/$2/$3/api.py
        touch plugins/$2/$3/stdlib.py
        touch plugins/$2/$3/settings.py
    fi
}

function help() {
    echo "$0 start|stop|restart|status"
}


case $1 in
    stop)
        stop
        ;;
    start)
        start
        ;;
    restart)
        restart
        ;;
    status)
        status
        ;;
    create_plugin)
        create_plugin $*
        ;;
    cron)
        cron
        ;;
    *)
        help
        exit 0
        ;;
esac
    
